import {defineStore} from 'pinia'
import {login,getRouters,getUserInfo} from '@/service/login/login'
import type { LoginFormData } from '../../types/login'
import router from '@/router'
import { localCache } from '@/utils/cache'
import { LOGIN_TOKEN, MENULIST,SCHOOLINFO } from '@/global/constans'
 //多处使用的字符串，建议用常量代替
const useLoginStore = defineStore('login',{
  state:()=>{
    return{
      loginInfo:{},
      token: localCache.getCache(LOGIN_TOKEN) ?? '',
      menuList: localCache.getCache(MENULIST) ?? [],
      schoolInfo: localCache.getCache(SCHOOLINFO) ?? {},
      userInfo: localCache.getCache('USERINFO')?? {}
    }
  },
  actions:{
    async loginAction(data:LoginFormData){
      let res = await login(data)
      let d = res.data
      this.loginInfo = d
      this.userInfo = d
      this.token = d.token
      localCache.setCache(LOGIN_TOKEN,d.token)
      localCache.setCache('USERINFO',JSON.stringify(d))
      if(data.remember){
        localCache.setCache('username',data.username)
        localCache.setCache('password',data.password)
      }else{
        localCache.removeCache('username')
        localCache.removeCache('password')
      }
      localCache.setCache('remember',data.remember)
      // 获取用户详细信息
      let userInfoResult = await getUserInfo(d.userId)
      // 获取路由
      let routerResult = await getRouters({phone:userInfoResult.data.phone})
      this.menuList = routerResult.data.list
      localCache.setCache(MENULIST, routerResult.data.list)
      // 动态添加路由
      routerResult.data.list.forEach((item:any)=>{
        if(item.component) {
          router.addRoute('main', {
            path: item.path,
            name: item.name,
            component: () => import(`@/views${item.component}`),
            meta: item.meta
          })
        }
      })
      console.log(router,'router')
      // 登录成功跳转
      setTimeout(()=>{
        router.push('/main')
      },300)
    },
    fnLoginOut(){
      this.token = ''
      this.menuList = []
      this.userInfo = {}
      localCache.clearCache()
      router.push('/login')
    }
  }
})

export default useLoginStore